package com.huang.eduorder.component;

import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hunag.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Component
public class SentinelBlockException implements UrlBlockHandler {
    @Override
    public void blocked(HttpServletRequest request, HttpServletResponse response, BlockException e) throws IOException {
        log.info("BlockExceptionHandler BlockException================"+e.getRule());
        R r=null;

        if(e instanceof FlowException){
            r=R.error().code(100).message(" 流量限制了，请稍后再试");
        } else if (e instanceof DegradeException) {
            r=R.error().code(100).message(" 服务降级了，请稍后再重试 ");
        } else if (e instanceof ParamFlowException) {
            r=R.error().code(100).message(" 热点参数被限制了，请稍后再试");
        }


        //返回json数据
        response.setStatus(500);
        response.setCharacterEncoding("utf-8");
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        new ObjectMapper().writeValue(response.getWriter(), r);
    }
    }

